package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;
import static com.tjvib.util.FormatUtil.isValidPhoneNumber;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tjvib.Constants;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.presenter.LoginPresenter;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.AppManager;
import com.tjvib.util.FormatUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.PressUtil;
import com.tjvib.util.SharedPreferencesUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.view.dialog.HintDialog;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class LoginActivity extends BaseActivity<LoginPresenter> {

    // isPsw.false=验证码 isPsw.true=密码
    private boolean isPsw = false, isAgree = false;
    private String phone, psw;

    private ImageView login_iv_back;
    private EditText login_et_phone, login_et_psw;
    private Button login_btn_sms, login_btn_login;
    private TextView login_tv_way, login_tv_psw;
    private CheckBox login_cb_agreement;
    private View login_v_agreement;

    private SmsCountDownTimer timer;

    private LoginPresenter loginPresenter = new LoginPresenter(this);

    // 倒计时
    private class SmsCountDownTimer extends CountDownTimer {

        public SmsCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            login_btn_sms.setEnabled(false);
            login_btn_sms.setClickable(false);
            login_btn_sms.setText(l / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            login_btn_sms.setText("重新获取");
            login_btn_sms.setEnabled(true);
            login_btn_sms.setClickable(true);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected boolean initView() {
        login_iv_back = findViewById(R.id.login_iv_back);
        login_iv_back.setClickable(true);
        login_iv_back.setOnClickListener(new OnSingleClickListener() {
            @Override
            public void onSingleClick(View view) {
                AppManager.getInstance().finishActivity();
            }
        });

        login_et_phone = findViewById(R.id.login_et_phone);
        login_et_psw = findViewById(R.id.login_et_psw);
        login_et_psw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        login_et_psw.setInputType(InputType.TYPE_CLASS_NUMBER);
        login_et_psw.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});

        login_btn_sms = findViewById(R.id.login_btn_sms);
        login_btn_sms.setOnClickListener(new OnSingleClickListener() {
            @Override
            public void onSingleClick(View view) {
                phone = login_et_phone.getText().toString().trim();
                if (phone.equals("") || phone == null) {
                    ToastUtil.show("请填写手机号");
                } else if (!isValidPhoneNumber(phone)) {
                    ToastUtil.show("手机号格式不正确");
                } else {
                    loginPresenter.getSmsCode(phone,
                            new Observer<BaseResponse>() {
                                @Override
                                public void onSubscribe(Disposable d) {
                                }

                                @Override
                                public void onNext(BaseResponse baseResponse) {
                                    if (baseResponse.getCode() == SUCCESS) {
                                        ToastUtil.show("发送成功");
                                        timer.start();
                                    } else
                                        ToastUtil.show("" + baseResponse.getMessage());
                                    LogUtil.i("login_btn_sms " + baseResponse.getCode() + " " + baseResponse.getMessage()
                                            + " " + baseResponse.getData());
                                }

                                @Override
                                public void onError(Throwable e) {
                                    LogUtil.e(e.toString());
                                    ToastUtil.show(e.getMessage());
                                }

                                @Override
                                public void onComplete() {
                                }
                            });
                }
            }
        });

        login_btn_login = findViewById(R.id.login_btn_login);
        login_btn_login.setOnClickListener(view -> {
            if (!isAgree || !login_cb_agreement.isChecked()) {
                HintDialog hintDialog = new HintDialog(this);
                hintDialog.showDialog(this, "提示", "请您点击确认"+getString(R.string.tv_service_agreement)+"，否则无法正常使用应用。",
                        v -> {
                            login_cb_agreement.setChecked(true);
                            hintDialog.dismiss();
                        }, v -> hintDialog.dismiss());
            } else {
                if (isPsw)
                    verifyPwd();
                else {
                    verifySmsCode();
                }
            }
        });

        login_tv_psw = findViewById(R.id.login_tv_psw);
        login_tv_way = findViewById(R.id.login_tv_way);
        login_tv_way.setClickable(true);
        login_tv_way.setOnClickListener(v -> {
            if (isPsw) {
                login_btn_sms.setVisibility(View.VISIBLE);
                if (timer == null) {
                    timer = new SmsCountDownTimer(60000, 1000);
                }
                login_tv_psw.setText("验证码");
                login_et_psw.setText("");
                login_et_psw.setHint("请输入验证码");
                login_et_psw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                login_et_psw.setInputType(InputType.TYPE_CLASS_NUMBER);
                login_et_psw.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                login_tv_way.setText("密码登录");
                login_btn_login.setText("登录/注册");
                isPsw = false;
            } else {
                login_btn_sms.setVisibility(View.GONE);
                clearTimer();
                login_tv_psw.setText("密码");
                login_et_psw.setText("");
                login_et_psw.setHint("请输入密码");
                login_et_psw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                login_et_psw.setInputType(InputType.TYPE_CLASS_TEXT);
                login_et_psw.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});
                login_tv_way.setText("验证码登录");
                login_btn_login.setText("登录");
                isPsw = true;
            }
        });

        login_cb_agreement = findViewById(R.id.login_cb_agreement);
        login_cb_agreement.setOnCheckedChangeListener((compoundButton, b) -> isAgree = b);

        login_v_agreement = findViewById(R.id.login_v_agreement);
        login_v_agreement.setOnClickListener(view -> {
            Intent intent = new Intent(LoginActivity.this, WebActivity.class);
//                intent.putExtra("URL", "file:///android_asset/agreement.html");
            intent.putExtra("URL", "http://122.152.206.37:8033/user-services-agreement.html");
            intent.putExtra("TITLE", "用户服务协议和隐私政策");
            startActivity(intent);
        });

        PressUtil.setPressChange(LoginActivity.this, login_iv_back, login_tv_way, login_btn_sms);

        return true;
    }

    @Override
    protected boolean initData() {
        isPsw = false;
        isAgree = false;

        return true;
    }

    @Override
    protected LoginPresenter genPresenter() {
        return new LoginPresenter(this);
    }


    private void verifyPwd() {
        phone = login_et_phone.getText().toString().trim();
        psw = login_et_psw.getText().toString();

        if (phone.isEmpty()) {
            ToastUtil.show("请输入手机号");
            return;
        }

        if (!isValidPhoneNumber(phone)) {
            ToastUtil.show("手机号格式不正确");
            return;
        }

        if (psw.isEmpty()) {
            ToastUtil.show("请输入密码");
            return;
        }

        loginPresenter.loginByPwd(phone, psw,
                new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        LogUtil.d(baseResponse.getCode() + "\n" + baseResponse.getMessage() + "\n" + baseResponse.getData());
                        if (baseResponse.getCode() == SUCCESS) {
                            String token = UserManager.getInstance().setInfo(String.valueOf(baseResponse.getData()));
                            if (!token.isEmpty())
                                SharedPreferencesUtil.saveToken(LoginActivity.this, token);

                            AppManager.getInstance().finishActivity(BootingActivity.class);
                            AppManager.getInstance().finishActivity();
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        } else {
                            showErrorDialog(baseResponse.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showErrorDialog(e.getMessage());
                        LogUtil.e(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


    private void verifySmsCode() {
        phone = login_et_phone.getText().toString().trim();
        psw = login_et_psw.getText().toString();

        if (phone.isEmpty()) {
            ToastUtil.show("请输入手机号");
            return;
        }

        if (!isValidPhoneNumber(phone)) {
            ToastUtil.show("手机号格式不正确");
            return;
        }

        if (psw.isEmpty()) {
            ToastUtil.show("请输入验证码");
            return;
        }

        if (!FormatUtil.isValidSmsCode(psw) && !isPsw) {
            ToastUtil.show("验证码格式不正确");
            return;
        }

        loginPresenter.loginBySms(phone, psw,
                new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        //解除订阅
                    }

                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        LogUtil.d(baseResponse.getCode() + "\n" + baseResponse.getMessage() + "\n" + baseResponse.getData());
                        if (baseResponse.getCode() == SUCCESS) {
                            String token = UserManager.getInstance().setInfo(String.valueOf(baseResponse.getData()));
                            if (!token.isEmpty())
                                SharedPreferencesUtil.saveToken(LoginActivity.this, token);

                            if(baseResponse.getMessage().contains("注册"))
                                startActivity(new Intent(LoginActivity.this, PwdActivity.class));
                            else {
                                AppManager.getInstance().finishActivity();
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            }
                        } else {
                            showErrorDialog(baseResponse.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showErrorDialog(e.getMessage());
                        LogUtil.e(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //发送事件时观察者回调(事件序列发送完毕)
                    }
                });
    }


    private void clearTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
            login_btn_sms.setText("获取验证码");
            login_btn_sms.setEnabled(true);
            login_btn_sms.setClickable(true);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        timer = new SmsCountDownTimer(60000, 1000);
    }

    @Override
    protected void onStop() {
        clearTimer();
        super.onStop();
    }
}